from fastapi import APIRouter, Depends, File, Form, UploadFile, HTTPException
from sqlalchemy.orm import Session
import uuid
from typing import List, Optional
import datetime

from ..database import get_db
from ..models import Course as CourseModel, User
from ..schemas import Course as CourseSchema, CourseCreate, CourseUpdate
from ..auth import get_current_active_user
from ..utils.files import save_icon_to_local

router = APIRouter(prefix="/api/chance/courses", tags=["courses"])

# 获取所有课程
@router.get("/", response_model=List[CourseSchema])
async def get_courses(
    skip: int = 0,
    limit: int = 10,
    title: Optional[str] = None,
    db: Session = Depends(get_db)
):
    query = db.query(CourseModel)
    
    if title:
        query = query.filter(CourseModel.title.contains(title))
    
    courses = query.offset(skip).limit(limit).all()
    return courses

# 创建课程
@router.post("/", response_model=CourseSchema)
async def create_course(
    title: str = Form(...),
    desc: str = Form(...),
    price: int = Form(...),
    book_num: int = Form(0),
    cover: UploadFile = File(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 保存封面图（如果有）
    cover_path = None
    if cover:
        course_id = str(uuid.uuid4())
        cover_path = save_icon_to_local(cover, course_id)
    
    # 创建课程记录
    course_data = CourseModel(
        title=title,
        desc=desc,
        price=price,
        book_num=book_num,
        cover=cover_path,
        creator_id=current_user.id,
        created_at=datetime.datetime.now(),
        updated_at=datetime.datetime.now()
    )
    
    db.add(course_data)
    db.commit()
    db.refresh(course_data)
    return course_data

# 获取单个课程
@router.get("/{course_id}", response_model=CourseSchema)
async def get_course(
    course_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if not course:
        raise HTTPException(status_code=404, detail="课程不存在")
    return course

# 更新课程
@router.put("/{course_id}", response_model=CourseSchema)
async def update_course(
    course_id: int,
    title: str = Form(None),
    desc: str = Form(None),
    price: int = Form(None),
    book_num: int = Form(None),
    cover: UploadFile = File(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if not course:
        raise HTTPException(status_code=404, detail="课程不存在")
    
    # 更新字段
    update_data = {}
    if title is not None:
        update_data['title'] = title
    if desc is not None:
        update_data['desc'] = desc
    if price is not None:
        update_data['price'] = price
    if book_num is not None:
        update_data['book_num'] = book_num
    
    # 更新封面图（如果有）
    if cover:
        cover_id = str(uuid.uuid4())
        cover_path = save_icon_to_local(cover, cover_id)
        update_data['cover'] = cover_path
    
    # 应用更新
    for key, value in update_data.items():
        setattr(course, key, value)
    
    course.updated_at = datetime.datetime.now()
    
    db.commit()
    db.refresh(course)
    
    return course

# ==================== 课程章节管理 ====================

from ..models import CourseCategory as CourseCategoryModel
from ..schemas import CourseCategory as CourseCategorySchema, CourseCategoryCreate, CourseCategoryUpdate

# 获取课程的所有章节
@router.get("/{course_id}/categories", response_model=List[CourseCategorySchema])
async def get_course_categories(
    course_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 验证课程是否存在
    course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if not course:
        raise HTTPException(status_code=404, detail="课程不存在")
    
    # 获取章节列表
    categories = db.query(CourseCategoryModel).filter(
        CourseCategoryModel.course_id == course_id,
        CourseCategoryModel.is_active == True
    ).order_by(CourseCategoryModel.sort_order).all()
    
    return categories

# 创建课程章节
@router.post("/{course_id}/categories", response_model=CourseCategorySchema)
async def create_course_category(
    course_id: int,
    code: str = Form(...),
    name: str = Form(...),
    content: str = Form(""),
    sort_order: int = Form(0),
    video: UploadFile = File(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 验证课程是否存在
    course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if not course:
        raise HTTPException(status_code=404, detail="课程不存在")
    
    # 保存视频文件（如果有）
    video_url = None
    if video:
        video_id = str(uuid.uuid4())
        video_url = save_icon_to_local(video, video_id)
        
    # 创建章节
    category_data = CourseCategoryModel(
        course_id=course_id,
        code=code,
        name=name,
        can_view=True,
        content=content,
        url=video_url,
        sort_order=sort_order,
        created_at=datetime.datetime.now(),
        updated_at=datetime.datetime.now()
    )
    
    db.add(category_data)
    db.commit()
    db.refresh(category_data)
    
    return category_data

# 更新课程章节
@router.put("/{course_id}/categories/{category_id}", response_model=CourseCategorySchema)
async def update_course_category(
    course_id: int,
    category_id: int,
    code: str = Form(None),
    name: str = Form(None),
    content: str = Form(None),
    sort_order: int = Form(None),
    video: UploadFile = File(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 验证课程是否存在
    course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if not course:
        raise HTTPException(status_code=404, detail="课程不存在")
    
    # 查找章节
    category_data = db.query(CourseCategoryModel).filter(
        CourseCategoryModel.id == category_id,
        CourseCategoryModel.course_id == course_id
    ).first()
    
    if not category_data:
        raise HTTPException(status_code=404, detail="章节不存在")
    
    # 更新字段
    if code is not None:
        category_data.code = code
    if name is not None:
        category_data.name = name
    if content is not None:
        category_data.content = content
    if sort_order is not None:
        category_data.sort_order = sort_order
        # 如果修改为第一章节，设置为可观看
        category_data.can_view = True
    
    # 更新视频文件（如果有新上传）
    if video:
        video_id = str(uuid.uuid4())
        video_url = save_icon_to_local(video, video_id)
        category_data.url = video_url
    
    category_data.updated_at = datetime.datetime.now()
    
    db.commit()
    db.refresh(category_data)
    
    return category_data

# 删除课程章节
@router.delete("/{course_id}/categories/{category_id}")
async def delete_course_category(
    course_id: int,
    category_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 验证课程是否存在
    course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if not course:
        raise HTTPException(status_code=404, detail="课程不存在")
    
    # 查找章节
    category_data = db.query(CourseCategoryModel).filter(
        CourseCategoryModel.id == category_id,
        CourseCategoryModel.course_id == course_id
    ).first()
    
    if not category_data:
        raise HTTPException(status_code=404, detail="章节不存在")
    
    # 软删除
    category_data.is_active = False
    category_data.updated_at = datetime.datetime.now()
    
    db.commit()
    
    return {"message": "章节删除成功"}
